
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Snake Game</title>
<style>
    #game-board {
        width: 400px;
        height: 400px;
        border: 1px solid black;
        position: relative;
    }

    .snake {
        width: 10px;
        height: 10px;
        background-color: black;
        position: absolute;
    }

    #food {
        width: 10px;
        height: 10px;
        background-color: red;
        position: absolute;
    }
</style>
</head>
<body>
<div id="game-board"></div>
<script>
    const gameBoard = document.getElementById('game-board');
    const snake = [{x: 200, y: 200}];
    let dx = 10;
    let dy = 0;
    let food = {x: 100, y: 100};

    function drawSnake() {
        gameBoard.innerHTML = '';
        snake.forEach(segment => {
            const snakeElement = document.createElement('div');
            snakeElement.style.left = segment.x + 'px';
            snakeElement.style.top = segment.y + 'px';
            snakeElement.classList.add('snake');
            gameBoard.appendChild(snakeElement);
        });
    }

    function drawFood() {
        const foodElement = document.createElement('div');
        foodElement.style.left = food.x + 'px';
        foodElement.style.top = food.y + 'px';
        foodElement.id = 'food';
        gameBoard.appendChild(foodElement);
    }

    function checkGameOver() {
        if (snake[0].x < 0 || snake[0].x >= 400 || snake[0].y < 0 || snake[0].y >= 400) {
            alert('你死了');
            location.reload(); // 重新加载页面，重新开始游戏
        }

        for (let i = 1; i < snake.length; i++) {
            if (snake[i].x === snake[0].x && snake[i].y === snake[0].y) {
                alert('Game Over! Your snake hit itself.');
                location.reload(); // 重新加载页面，重新开始游戏
            }
        }
    }

    function moveSnake() {
        const head = {x: snake[0].x + dx, y: snake[0].y + dy};
        snake.unshift(head);
        if (head.x === food.x && head.y === food.y) {
            food.x = Math.floor(Math.random() * 40) * 10;
            food.y = Math.floor(Math.random() * 40) * 10;
        } else {
            snake.pop();
        }

        checkGameOver();
        drawSnake();
        drawFood();
    }

    drawSnake();
    drawFood();

    document.addEventListener('keydown', (e) => {
        if (e.key === 'ArrowUp' && dy !== 10) {
            dx = 0;
            dy = -10;
        } else if (e.key === 'ArrowDown' && dy !== -10) {
            dx = 0;
            dy = 10;
        } else if (e.key === 'ArrowLeft' && dx !== 10) {
            dx = -10;
            dy = 0;
        } else if (e.key === 'ArrowRight' && dx !== -10) {
            dx = 10;
            dy = 0;
        }
    });

    setInterval(moveSnake, 100);
</script>
</body>
</html>
